package com.newasia.search.services;

import com.google.common.collect.Lists;
import com.newasia.search.InitDataService;
import com.newasia.search.converter.ProductConverter;
import com.newasia.search.dal.entitys.SkuKey;
import com.newasia.search.dal.entitys.SpuKey;
import com.newasia.search.dal.persistence.ItemMapper;
import com.newasia.search.dto.SkuDto;
import com.newasia.search.dto.SpuDto;
import com.newasia.search.entity.SkuDocument;
import com.newasia.search.entity.SpuDocument;
import com.newasia.search.repository.SkuRepository;
import com.newasia.search.repository.SpuRepository;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.aggregation.AggregatedPage;

import java.util.ArrayList;
import java.util.List;

/**
 * 腾讯课堂搜索【咕泡学院】
 * 官网：www.gupaoedu.com
 * 风骚的Mic 老师
 * create-date: 2019/9/2-22:05
 */
@Slf4j
@Service
public class InitDataServiceImpl implements InitDataService {
    @Autowired
    private SkuRepository skuRepository;

    @Autowired
    private SpuRepository spuRepository;

    @Autowired
    ItemMapper itemMapper;

    @Autowired
    ProductConverter productConverter;

    @Override
    public void initItems() {
        List<SkuKey> skuKeys=itemMapper.selectSkuKey();
        List<SpuKey> spuKeys=itemMapper.selectSpuKey();
        skuKeys.parallelStream().forEach(sku->{
            SkuDocument dto = productConverter.sku2Document(sku);
            skuRepository.save(dto);
        });
        spuKeys.parallelStream().forEach(spu->{
            SpuDocument dto = productConverter.spu2Document(spu);
            spuRepository.save(dto);
        });
    }

    @Override
    public void deleteItem() {
        skuRepository.deleteAll();
        spuRepository.deleteAll();
    }

    @Override
    public List<SpuDto> findSpuAll() {
        AggregatedPage<SpuDocument> search = (AggregatedPage)spuRepository.findAll();
        ArrayList<SpuDocument> SpuDocuments = Lists.newArrayList(search);
        return productConverter.spu2Dto(SpuDocuments);
    }

    @Override
    public List<SkuDto> findSkuAll() {
        AggregatedPage<SkuDocument> search = (AggregatedPage)skuRepository.findAll();
        ArrayList<SkuDocument> SkuDocuments = Lists.newArrayList(search);
        return productConverter.skuDto(SkuDocuments);
    }
}
